// ExamPublish.vue
<template>
  <div class="exam-publish-container">
    <!-- 标题栏 -->
    <div class="header">
      <el-button icon="el-icon-back" @click="goBack">返回</el-button>
      <h1>发布考试</h1>
    </div>

    <!-- 考试基本信息 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <h2>基本信息</h2>
        </div>
      </template>
      <el-form :model="examForm" :rules="examRules" ref="examFormRef" label-width="100px">
        <el-form-item label="考试名称" prop="examName" required>
          <el-input v-model="examForm.examName" placeholder="请输入考试名称"></el-input>
        </el-form-item>

        <el-form-item label="考试时间" required>
          <el-row :gutter="20">
            <el-col :span="11">
              <el-form-item prop="startTime">
                <el-date-picker v-model="examForm.startTime" type="datetime" placeholder="开始时间"
                  style="width: 100%"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">至</el-col>
            <el-col :span="11">
              <el-form-item prop="endTime">
                <el-date-picker v-model="examForm.endTime" type="datetime" placeholder="结束时间"
                  style="width: 100%"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="考试说明">
          <el-input v-model="examForm.description" type="textarea" :rows="4" placeholder="请输入考试说明"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题目管理 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <h2>题目管理</h2>
          <div class="question-actions">
            <el-button type="success" @click="createNewQuestion">
              新建题目
              <i class="el-icon-edit el-icon--right"></i>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 已选题目列表 -->
      <div v-if="selectedQuestions.length > 0" class="selected-questions">
        <div class="selected-count">
          已选题目 ({{ selectedQuestions.length }})
        </div>

        <el-table ref="questionTable" :data="filteredQuestions" border style="width: 100%" row-key="id"
          @sort-change="handleSortChange" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column prop="content" label="题目" show-overflow-tooltip>
            <template #default="scope">
              <div v-html="formatMathFormula(scope.row.content)"></div>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="课程" width="100"></el-table-column>
          <el-table-column prop="type" label="题型" width="100">
            <template #default="scope">
              <el-tag :type="getQuestionTypeTag(scope.row.type)">
                {{ formatQuestionType(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="100">
            <template #default="scope">
              <el-rate v-model="scope.row.difficulty" disabled show-score text-color="#ff9900"
                score-template="{value}"></el-rate>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="batch-actions">
          <el-button type="danger" :disabled="multipleSelection.length === 0" @click="batchDelete">
            批量删除
          </el-button>
        </div>
      </div>
      <el-empty v-else description="暂无题目，请新建题目"></el-empty>
    </el-card>

    <!-- 发布按钮 -->
    <div class="action-buttons">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="previewExam">预览</el-button>
      <el-button type="success" @click="publishExam" :disabled="!canPublish">发布考试</el-button>
    </div>

    <!-- 预览考试弹窗 -->
    <el-dialog v-model="previewDialogVisible" title="考试预览" width="70%" :before-close="handlePreviewClose">
      <div class="exam-preview">
        <div class="preview-header">
          <h1>{{ examForm.examName }}</h1>
          <div class="exam-info">
            <p>考试时间：{{ formatDateTime(examForm.startTime) }} 至 {{ formatDateTime(examForm.endTime) }}</p>
            <p v-if="examForm.description">考试说明：{{ examForm.description }}</p>
          </div>
        </div>

        <div class="preview-content">
          <template v-for="(group, groupIndex) in groupedQuestions" :key="groupIndex">
            <div class="question-section">
              <h3>{{ formatQuestionType(group.type) }}（{{ group.questions.length }}题）</h3>
              <div class="question-list">
                <div v-for="(question, index) in group.questions" :key="question.id" class="question-item">
                  <div class="question-header">
                    <span class="question-number">{{ index + 1 }}.</span>
                    <span class="question-content" v-html="formatMathFormula(question.content)"></span>
                    <span class="question-score">({{ question.score }}分)</span>
                  </div>

                  <div class="question-options" v-if="question.type === 'single' || question.type === 'multiple'">
                    <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                      <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                      <span class="option-content" v-html="formatMathFormula(option.content)"></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>

    <!-- 新建/编辑题目弹窗 -->
    <el-dialog v-model="questionDialogVisible" :title="questionDialogType === 'create' ? '新建题目' : '编辑题目'" width="60%"
      :before-close="handleQuestionDialogClose">
      <el-form :model="questionForm" :rules="questionRules" ref="questionFormRef" label-width="100px">
        <el-form-item label="题型" prop="type" required>
          <el-select v-model="questionForm.type" placeholder="请选择题型">
            <el-option v-for="item in questionTypes" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程" prop="category" required>
          <el-cascader v-model="questionForm.categoryPath" :options="categoryOptions" clearable placeholder="请选择课程分类"
            @change="handleCategoryChange"></el-cascader>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty" required>
          <el-rate v-model="questionForm.difficulty" show-score text-color="#ff9900"></el-rate>
        </el-form-item>

        <el-form-item label="分值" prop="score" required>
          <el-input-number v-model="questionForm.score" :min="1" :max="100"></el-input-number>
        </el-form-item>

        <el-form-item label="题干" prop="content" required>
          <el-input v-model="questionForm.content" type="textarea" :rows="4"
            placeholder="支持 LaTeX 公式，如：$x^2 + y^2 = z^2$"></el-input>
        </el-form-item>

        <!-- 选择题选项 -->
        <template v-if="questionForm.type === 'single' || questionForm.type === 'multiple'">
          <el-divider content-position="left">选项</el-divider>
          <div v-for="(option, index) in questionForm.options" :key="index" class="option-form-item">
            <el-form-item :label="'选项' + String.fromCharCode(65 + index)" :prop="'options.' + index + '.content'"
              :rules="{ required: true, message: '选项内容不能为空', trigger: 'blur' }">
              <div class="option-input-group">
                <el-input v-model="option.content" placeholder="请输入选项内容"></el-input>
                <el-checkbox v-model="option.isCorrect" label="正确答案"
                  :disabled="questionForm.type === 'single' && hasSelectedCorrectOption(index)"></el-checkbox>
                <el-button type="danger" icon="el-icon-delete" circle @click="removeOption(index)"
                  :disabled="questionForm.options?.length <= 2"></el-button>
              </div>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" @click="addOption"
              :disabled="questionForm.options.length >= 6">
              添加选项
            </el-button>
          </el-form-item>
        </template>

        <!-- 判断题答案 -->
        <template v-else-if="questionForm.type === 'truefalse'">
          <el-divider content-position="left">答案</el-divider>
          <el-form-item label="正确答案" prop="answer" required>
            <el-radio-group v-model="questionForm.answer">
              <el-radio :label="true">正确</el-radio>
              <el-radio :label="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <!-- 填空题答案 -->
        <template v-else-if="questionForm.type === 'fill'">
          <el-divider content-position="left">答案</el-divider>
          <div v-for="(blank, index) in questionForm.blanks" :key="index" class="blank-form-item">
            <el-form-item :label="'空格' + (index + 1)" :prop="'blanks.' + index + '.answer'"
              :rules="{ required: true, message: '答案不能为空', trigger: 'blur' }">
              <div class="blank-input-group">
                <el-input v-model="blank.answer" placeholder="请输入答案"></el-input>
                <el-button type="danger" icon="el-icon-delete" circle @click="removeBlank(index)"
                  :disabled="questionForm.blanks.length <= 1"></el-button>
              </div>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" @click="addBlank">
              添加空格
            </el-button>
          </el-form-item>
        </template>

        <!-- 问答题/计算题答案 -->
        <template v-else>
          <el-divider content-position="left">答案</el-divider>
          <el-form-item label="参考答案" prop="answer">
            <el-input v-model="questionForm.answer" type="textarea" :rows="4" placeholder="请输入参考答案"></el-input>
          </el-form-item>
        </template>

        <el-form-item label="解析" prop="explanation">
          <el-input v-model="questionForm.explanation" type="textarea" :rows="4" placeholder="请输入题目解析（可选）"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="questionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveQuestionForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { teacherApi } from '@/api/teacherApi';

interface ExamForm {
  examName: string;
  startTime: Date | null;
  endTime: Date | null;
  description: string;
}

interface QuestionOption {
  content: string;
  isCorrect: boolean;
}

interface QuestionBlank {
  answer: string;
}

interface Question {
  id: string;
  content: string;
  type: string;
  category: string;
  categoryPath: string[];
  difficulty: number;
  score: number;
  options?: QuestionOption[];
  answer?: unknown;
  blanks?: QuestionBlank[];
  explanation?: string;
}



interface QuestionGroup {
  type: string;
  questions: Question[];
}

export default defineComponent({
  name: 'ExamPublish',
  setup() {
    // 表单引用
    const examFormRef = ref<FormInstance>();
    const questionFormRef = ref<FormInstance>();

    // 考试表单数据
    const examForm = reactive<ExamForm>({
      examName: '',
      startTime: null,
      endTime: null,
      description: '',
    });

    // 考试表单校验规则
    const examRules = reactive<FormRules>({
      examName: [
        { required: true, message: '请输入考试名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        {
          validator: (rule, value, callback) => {
            if (value && examForm.startTime && value <= examForm.startTime) {
              callback(new Error('结束时间必须晚于开始时间'));
            } else {
              callback();
            }
          },
          trigger: 'change'
        }
      ]
    });

    // 题目表单数据
    const questionForm = reactive<Question>({
      id: '',
      content: '',
      type: 'single',
      category: '',
      categoryPath: [],
      difficulty: 3,
      score: 5,
      options: [
        { content: '', isCorrect: false },
        { content: '', isCorrect: false },
        { content: '', isCorrect: false },
        { content: '', isCorrect: false }
      ],
      answer: '',
      blanks: [{ answer: '' }],
      explanation: ''
    });

    // 题目表单校验规则
    const questionRules = reactive<FormRules>({
      type: [
        { required: true, message: '请选择题型', trigger: 'change' }
      ],
      category: [
        { required: true, message: '请选择课程分类', trigger: 'change' }
      ],
      difficulty: [
        { required: true, message: '请选择难度', trigger: 'change' }
      ],
      score: [
        { required: true, message: '请输入分值', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入题干', trigger: 'blur' }
      ]
    });

    // 状态变量
    const previewDialogVisible = ref(false);
    const questionDialogVisible = ref(false);
    const questionDialogType = ref<'create' | 'edit'>('create');
    const selectedQuestions = ref<Question[]>([]);
    const multipleSelection = ref<Question[]>([]);
    const searchQuery = ref('');

    // 模拟数据 - 实际项目中应该从API获取
    const questionTypes = [
      { value: 'single', label: '单选题' },
      { value: 'multiple', label: '多选题' },
      { value: 'truefalse', label: '判断题' },
      { value: 'fill', label: '填空题' },
      { value: 'shortanswer', label: '简答题' },
      { value: 'calculation', label: '计算题' }
    ];

    const categoryOptions = ref([
      {
        value: 'math',
        label: '数学',
        children: [
          { value: 'algebra', label: '代数' },
          { value: 'geometry', label: '几何' },
          { value: 'calculus', label: '微积分' }
        ]
      },
      {
        value: 'physics',
        label: '物理',
        children: [
          { value: 'mechanics', label: '力学' },
          { value: 'electromagnetism', label: '电磁学' },
          { value: 'thermodynamics', label: '热力学' }
        ]
      },
      {
        value: 'chemistry',
        label: '化学',
        children: [
          { value: 'organic', label: '有机化学' },
          { value: 'inorganic', label: '无机化学' },
          { value: 'physical', label: '物理化学' }
        ]
      }
    ]);

    // 模拟从后端获取的题目
    const fetchMockQuestions = async () => {
      try {
        const response = await teacherApi.getQuestions(); // 调用 teacherApi 获取问题列表
        if (response.code === 200) {
          selectedQuestions.value = response.data.map((item: any) => {
            // 对 JSON 字符串进行解析
            const parsedOptions = item.options ? JSON.parse(item.options) : null;
            const parsedBlanks = item.blanks ? JSON.parse(item.blanks) : null;
            const parsedAnswer = item.answer ? JSON.parse(item.answer) : null;

            // 如果是选择题，确保选项的 isCorrect 字段正确映射
            if (item.type === 'single' || item.type === 'multiple') {
              parsedOptions.forEach(option => {
                option.isCorrect = option.is_correct; // 将 is_correct 映射到 isCorrect
                delete option.is_correct; // 删除原始的 is_correct 字段
              });
            }

            return {
              id: item.id.toString(),
              content: item.content,
              type: item.type,
              category: item.category,
              categoryPath: item.categoryPath, // 如果后端返回的是路径数组，请在这里进行解析
              difficulty: item.difficulty,
              score: item.score,
              options: parsedOptions,
              blanks: parsedBlanks,
              answer: parsedAnswer,
            };
          });
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        console.error('获取问题列表失败:', error);
        ElMessage.error('获取问题列表失败');
      }
    };
    // 计算属性
    const filteredQuestions = computed(() => {
      if (!searchQuery.value) return selectedQuestions.value;

      return selectedQuestions.value.filter(q =>
        q.content.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        q.category.toLowerCase().includes(searchQuery.value.toLowerCase())
      );
    });

    const groupedQuestions = computed(() => {
      const groups: Record<string, QuestionGroup> = {};

      selectedQuestions.value.forEach(question => {
        if (!groups[question.type]) {
          groups[question.type] = {
            type: question.type,
            questions: []
          };
        }

        groups[question.type].questions.push(question);
      });

      return Object.values(groups);
    });

    const canPublish = computed(() => {
      return examForm.examName &&
        examForm.startTime &&
        examForm.endTime &&
        selectedQuestions.value.length > 0;
    });

    // 方法
    const goBack = () => {
      ElMessageBox.confirm('确定要返回吗？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('返回上一页');
      }).catch(() => { });
    };

    const handleSortChange = ({ prop, order }: { prop: string, order: string }) => {
      if (!prop) return;

      const sortFn = (a: any, b: any) => {
        if (order === 'ascending') {
          return a[prop] > b[prop] ? 1 : -1;
        } else {
          return a[prop] < b[prop] ? 1 : -1;
        }
      };

      selectedQuestions.value.sort(sortFn);
    };

    const handleSelectionChange = (selection: Question[]) => {
      multipleSelection.value = selection;
    };

    const handleEdit = (row: Question) => {
      // 确保在编辑时正确处理选项的 isCorrect 状态
      if (row.type === 'single' || row.type === 'multiple') {
        row.options?.forEach(option => {
          option.isCorrect = option.isCorrect; // 确保 isCorrect 被正确初始化
        });
      }

      Object.assign(questionForm, JSON.parse(JSON.stringify(row))); // 深拷贝避免引用问题
      questionDialogType.value = 'edit';
      questionDialogVisible.value = true;
    };

    const handleDelete = (row: Question) => {
      ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        selectedQuestions.value = selectedQuestions.value.filter(q => q.id !== row.id);
        ElMessage.success('删除成功');
      }).catch(() => { });
    };

    const batchDelete = () => {
      if (multipleSelection.value.length === 0) return;

      ElMessageBox.confirm(`确定要删除选中的 ${multipleSelection.value.length} 个题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = multipleSelection.value.map(q => q.id);
        selectedQuestions.value = selectedQuestions.value.filter(q => !selectedIds.includes(q.id));
        ElMessage.success('批量删除成功');
      }).catch(() => { });
    };


    const createNewQuestion = () => {
      // 如果已有题目，获取最大id值，否则设置为0
      const maxId = selectedQuestions.value.length > 0
        ? Math.max(...selectedQuestions.value.map(q => parseInt(q.id)), 0)
        : 0;

      Object.assign(questionForm, {
        id: (maxId + 1).toString(), // 新题目id为当前最大id加1
        content: '',
        type: 'single',
        category: '',
        categoryPath: [],
        difficulty: 3,
        score: 5,
        options: [
          { content: '', isCorrect: false },
          { content: '', isCorrect: false },
          { content: '', isCorrect: false },
          { content: '', isCorrect: false }
        ],
        answer: '',
        blanks: [{ answer: '' }],
        explanation: ''
      });

      questionDialogType.value = 'create';
      questionDialogVisible.value = true;
    };
    const handleQuestionDialogClose = (done: () => void) => {
      ElMessageBox.confirm('确认关闭？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => { });
    };

    const saveQuestionForm = () => {
      questionFormRef.value?.validate((valid) => {
        if (!valid) return false;

        if ((questionForm.type === 'single' || questionForm.type === 'multiple') &&
          questionForm.options &&
          !questionForm.options.some(opt => opt.isCorrect)) {
          ElMessage.error('请至少选择一个正确答案');
          return false;
        }

        if (questionForm.type === 'single' &&
          questionForm.options &&
          questionForm.options.filter(opt => opt.isCorrect).length > 1) {
          ElMessage.error('单选题只能有一个正确答案');
          return false;
        }

        const questionData = JSON.parse(JSON.stringify(questionForm));

        // 确保 id 是数值型
        if (!questionData.id) {
          const maxId = selectedQuestions.value.length > 0
            ? Math.max(...selectedQuestions.value.map(q => parseInt(q.id)), 0)
            : 0;
          questionData.id = (maxId + 1).toString();
        }

        // 处理选项字段
        if (questionData.type === 'single' || questionData.type === 'multiple') {
          questionData.options?.forEach(option => {
            option.is_correct = option.isCorrect;
            delete option.isCorrect;
          });
        }

        if (questionDialogType.value === 'create') {
          selectedQuestions.value.push(questionData);
          ElMessage.success('新建题目成功');
        } else {
          const index = selectedQuestions.value.findIndex(q => q.id === questionData.id);
          if (index !== -1) {
            selectedQuestions.value[index] = questionData;
            ElMessage.success('更新题目成功');
          }
        }

        questionDialogVisible.value = false;
      });
    };
    const hasSelectedCorrectOption = (currentIndex: number) => {
      if (questionForm.type !== 'single') return false;
      return questionForm.options && questionForm.options.some((opt, index) =>
        index !== currentIndex && opt.isCorrect
      );
    };

    const addOption = () => {
      if (questionForm.options && questionForm.options.length < 6) {
        questionForm.options.push({ content: '', isCorrect: false });
      }
    };

    const removeOption = (index: number) => {
      if (questionForm.options && questionForm.options.length > 2) {
        questionForm.options.splice(index, 1);
      }
    };

    const addBlank = () => {
      if (questionForm.blanks) {
        questionForm.blanks.push({ answer: '' });
      }
    };

    const removeBlank = (index: number) => {
      if (questionForm.blanks && questionForm.blanks.length > 1) {
        questionForm.blanks.splice(index, 1);
      }
    };

    const handleCategoryChange = (value: any) => {
      if (value && value.length > 0) {
        const categoryLabels = value.map((val: string, index: number) => {
          const option = index === 0
            ? categoryOptions.value.find(opt => opt.value === val)
            : categoryOptions.value
              .find(opt => opt.value === value[0])
              ?.children?.find(child => child.value === val);

          return option ? option.label : '';
        });

        questionForm.category = categoryLabels.join(' - ');
      } else {
        questionForm.category = '';
      }
    };

    const previewExam = () => {
      if (!examForm.examName) {
        ElMessage.warning('请先填写考试名称');
        return;
      }

      if (selectedQuestions.value.length === 0) {
        ElMessage.warning('请先添加题目');
        return;
      }

      previewDialogVisible.value = true;
    };

    const handlePreviewClose = (done: () => void) => {
      done();
    };

    //发布考试
    const publishExam = () => {
      if (!canPublish.value) {
        ElMessage.warning('请完善考试信息');
        return;
      }

      examFormRef.value?.validate((valid) => {
        if (!valid) return false;

        // 创建 examRequest 对象
        const examRequest = {
          name: examForm.examName,
          startTime: examForm.startTime!.toISOString(),
          endTime: examForm.endTime!.toISOString(),
          description: examForm.description,
          questions: selectedQuestions.value.map(question => {
            // 确保 id 是数值型
            const id = parseInt(question.id);

            // 确保 options 是字符串类型（如果后端期望字符串）
            const optionsStr = question.options ? JSON.stringify(question.options) : null;
            // 确保 blanks 是字符串类型（如果后端期望字符串）
            const blanksStr = question.blanks ? JSON.stringify(question.blanks) : null;
            // 确保 answer 字段的类型正确（根据后端实体类调整）
            const answerStr = question.answer ? JSON.stringify(question.answer) : null;

            return {
              ...question,
              id,
              options: optionsStr,
              blanks: blanksStr,
              answer: answerStr
            };
          })
        };
        console.log(examRequest);

        // 调用 teacherApi 的 publishExam 方法
        teacherApi.publishExam(examRequest)
          .then(response => {
            if (response.code === 200) {
              ElMessage.success(response.msg || '考试发布成功');
              // 清空表单
              examFormRef.value?.resetFields();
              selectedQuestions.value = [];
            } else {
              ElMessage.error(response.msg || '发布考试失败');
            }
          })
          .catch(error => {
            console.error('发布考试失败:', error);
            ElMessage.error('发布考试失败');
          });
      });
    };

    const resetForm = () => {
      ElMessageBox.confirm('确定要重置所有内容吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        examFormRef.value?.resetFields();
        selectedQuestions.value = [];
        ElMessage.success('已重置所有内容');
      }).catch(() => { });
    };

    const formatMathFormula = (text: string) => {
      return text.replace(/\$([^$]+)\$/g, '<span class="math-formula">$1</span>');
    };

    const formatQuestionType = (type: string) => {
      const typeObj = questionTypes.find(t => t.value === type);
      return typeObj ? typeObj.label : type;
    };

    const getQuestionTypeTag = (type: string) => {
      switch (type) {
        case 'single':
          return 'success';
        case 'multiple':
          return 'warning';
        case 'truefalse':
          return 'info';
        case 'fill':
          return 'primary';
        case 'shortanswer':
          return 'danger';
        default:
          return '';
      }
    };

    const formatDateTime = (date: Date | null) => {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };

    onMounted(() => {
      fetchMockQuestions();
    });

    return {
      examForm,
      examFormRef,
      examRules,
      questionForm,
      questionFormRef,
      questionRules,
      previewDialogVisible,
      questionDialogVisible,
      questionDialogType,
      selectedQuestions,
      multipleSelection,
      searchQuery,
      questionTypes,
      categoryOptions,
      filteredQuestions,
      groupedQuestions,
      canPublish,
      goBack,
      handleSortChange,
      handleSelectionChange,
      handleEdit,
      handleDelete,
      batchDelete,
      createNewQuestion,
      handleQuestionDialogClose,
      saveQuestionForm,
      hasSelectedCorrectOption,
      addOption,
      removeOption,
      addBlank,
      removeBlank,
      handleCategoryChange,
      previewExam,
      handlePreviewClose,
      publishExam,
      resetForm,
      formatMathFormula,
      formatQuestionType,
      getQuestionTypeTag,
      formatDateTime
    };
  }
});
</script>

<style scoped>
.exam-publish-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin-left: 15px;
  font-size: 22px;
  color: #303133;
}

.section-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.question-actions {
  display: flex;
  align-items: center;
}

.selected-questions {
  margin-top: 10px;
}

.selected-count {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.batch-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.preview-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.preview-header h1 {
  font-size: 22px;
  margin-bottom: 10px;
}

.exam-info {
  color: #606266;
  font-size: 14px;
}

.question-section {
  margin-bottom: 20px;
}

.question-section h3 {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #dcdfe6;
}

.question-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.question-number {
  margin-right: 5px;
  font-weight: 500;
}

.question-content {
  flex: 1;
}

.question-score {
  color: #e6a23c;
  margin-left: 10px;
}

.question-options {
  padding-left: 20px;
}

.option-item {
  margin-bottom: 5px;
  display: flex;
}

.option-label {
  margin-right: 5px;
}

.option-content {
  flex: 1;
}

.option-form-item {
  margin-bottom: 5px;
}

.option-input-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.blank-form-item {
  margin-bottom: 5px;
}

.blank-input-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.math-formula {
  font-style: italic;
  color: #409eff;
}

@media screen and (max-width: 992px) {
  .question-bank-container {
    flex-direction: column;
  }
}
</style>
